import type { ListOption, ConfigMap } from "../../../api/k8s/types";

import { useK8SApi } from "../../../api/k8s/k8s";
import { SourceMan } from "../providers/sourceCtl";
import type { Ref } from "vue";
const { configMapRepo } = useK8SApi();

class ConfigMapProvider extends SourceMan<ConfigMap> {
  get configMapList(): Ref<ConfigMap[]> {
    return this.srcList;
  }

  // 获取节点列表
  getConfigMaps = async (req?: ListOption) => {
    const res = await configMapRepo.getConfigMap({
      ...(req || this.searchQuery),
      continue: this.continue,
      limit: this.pager.limit.value
    });
    if (res.ok) {
      this.continue = res.data.metadata.continue;
      this.srcList.value = res.data.items;
      this.pager.total.value =
        res.data.metadata.remainingItemCount ?? res.data.items.length;
    }
  };

  // 获取节点详情
  getConfigMapDetails = async (name: string) => {
    const res = await configMapRepo.getConfigMapDetail({ name });
    if (res.ok) {
      this.srcDetail.value = res.data;
      this.srcYamlContent.value = this.objectToYaml(res.data);
      this.yamlDialog.value = true;
    }
  };

  // 更新节点
  updateConfigMap = async (node?: ConfigMap) => {
    const res = await configMapRepo.updateConfigMap(node);
    if (res.ok) {
      this.refreshConfigMapList();
    }
  };

  // delete
  deleteConfigMap = async (name: string) => {
    const res = await configMapRepo.deleteConfigMap({ name });
    if (res.ok) {
      this.refreshConfigMapList();
    }
  };

  refreshConfigMapList = async () => {
    this.continue = undefined;
    await this.getConfigMaps({});
  };
}

export default new ConfigMapProvider();
